<?php

namespace app\controller\api;

use app\model\api\GenshinCategory;
use app\model\api\GenshinCollect;
use app\model\api\GenshinLike;
use app\model\api\GenshinRole;
use app\model\api\GenshinTeam;
use app\service\api\GenshinServiceFacade;
use app\service\ConfServiceFacade;
use laytp\controller\Api;
use laytp\library\Tree;
use think\exception\ValidateException;
use think\Facade;
use think\facade\Db;
use think\Model;

/**
 * Class Genshin
 * @package app\index\controller
 */
class Genshin extends Api
{

    /**
     * 帖子url
     * @return \think\response\Json
     * @throws \Exception
     */
    public function targetUrl()
    {
        try{
            $url = ConfServiceFacade::get('system.basic.articleurl');
            return $this->success('success',$url);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }

    }

    /**
     * 分析原神url
     * @return \think\response\Json
     * @throws \Exception
     */
    public function parse()
    {
        $data = input('post.');
        $url = !empty($data['url'])?$data['url']:"";

        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('add')
                ->check([
                    'url' => $url
                ]);

            $parse_res = GenshinServiceFacade::parse($url);
            if(!is_numeric($parse_res)){
                return $this->error($parse_res,-1);
            }

            $list = (new \app\model\api\GenshinRecord())->getRecordList($parse_res);
            $result = GenshinServiceFacade::dataAnalysis($list);

            $result['uid'] = $parse_res;
            return $this->success('success',$result);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }

    }


    /**
     * 历史分析原神
     * @return \think\response\Json
     * @throws \Exception
     */
    public function history()
    {
        $data = input('post.');
        $uid = !empty($data['uid'])?$data['uid']:'';
        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('history')
                ->check([
                    'uid' => $uid
                ]);

            //获取历史抽卡记录
            $list = (new \app\model\api\GenshinRecord())->getRecordList($uid);
            if(empty($list)){
                $this->error('uid is not found',-1);
            }

            $result = GenshinServiceFacade::dataAnalysis($list);

            $result['uid'] = $uid;
            return $this->success('success',$result);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }

    }


    /**
     * 原神角色列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function roleList(){
        try{
            $list = (new \app\model\api\GenshinRole())->getRoleList();
            return $this->success('success',$list);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }
    }


    /**
     * 原神标签列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function tagList(){
        try{
            $list = (new \app\model\api\GenshinTeam())->getTagList();
            return $this->success('success',$list);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }
    }

    /**
     * 通关关卡
     * @return false|string|\think\response\Json
     */
    public function teamFilter(){
        try{
            $post = input('post.');
            if(isset($post['type'])&&!empty($post['type'])){
                $sourceData = (new GenshinCategory())->whereNotIn('id',array_diff([1,2],[$post['type']]))->where('is_show' ,1)->order('sort desc')->cache(true)->select()->toArray();
            }else{
                $sourceData = (new GenshinCategory())->where('is_show' ,1)->order('sort desc')->cache(true)->select()->toArray();
            }
            $menuTreeObj = Tree::instance();
            $menuTreeObj->init($sourceData);
            $data = $menuTreeObj->getRootTrees();

            $return = [];
            foreach($data as $item){
                $parent = [
                    'name' => $item['name'],
                    'id' => $item['id'],
                ];
                if(!empty($item['children'])){
                    foreach($item['children'] as $sub_item){
                        $sub_parent = [
                            'name' => $sub_item['name'],
                            'id' => $sub_item['id'],
                        ];
                        if(!empty($sub_item['children'])){
                            foreach($sub_item['children'] as $chiid){
                                $sub_parent['list'][] = array(
                                    'name' => $chiid['name'],
                                    'id' => $chiid['id']
                                );
                            }
                        }
                        $parent['list'][] = $sub_parent;
                    }

                }

                $return[] = $parent;
            }
            if(isset($post['type'])&&!empty($post['type'])){
                //降维返回
                $new_return = [];
                foreach ($return as $item){
                    if(isset($item['list'])&&count($item['list'])>0){
                        foreach ($item['list'] as $ite){
                            $new_return[]= $ite;
                        }
                    }
                }
                $return = $new_return;
            }

            return $this->success('success',$return);
        }catch (\Exception $e){
            return $this->exceptionError($e);
        }

    }

    /**
     * 查询角色信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function roleDetail(){
        $data = input('post.');
        $avatar_id = !empty($data['role_id'])?$data['role_id']:'';
        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('info')
                ->check([
                    'avatar_id' => $avatar_id
                ]);

            $detail = GenshinServiceFacade::roleDetail($avatar_id);
            return $this->success('success',$detail);

        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }
    }

    /**
     * 角色升级材料计算
     */
    public function roleLevel(){
        $data = input('post.');
        $avatar_id = !empty($data['role_id'])?$data['role_id']:"";
        $avatar_level_current = !empty($data['start_level'])?$data['start_level']:"";
        $avatar_level_target = !empty($data['end_level'])?$data['end_level']:"";
        $skill_list = !empty($data['skill_list'])?$data['skill_list']:"";

        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('level')
                ->check([
                    'avatar_id' => $avatar_id,
                    'avatar_level_current' => $avatar_level_current,
                    'avatar_level_target' => $avatar_level_target,
                    'skill_list' => $skill_list,
                ]);

            $skill = (new GenshinRole())->where('id',$avatar_id)->cache(true)->find()->toArray();

            $roleData = GenshinServiceFacade::roleLevel($avatar_id,$avatar_level_current,$avatar_level_target);
            $skillData = GenshinServiceFacade::skillLevel($avatar_id,$skill_list);
            return $this->success('success',[
                'rolematerial' => $roleData,
                'talentmaterial' => $skillData,
                'skill'  => json_decode($skill['skill'],true)
            ]);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }
    }

    /**
     * 组队列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function teamList(){
        $data = input('post.');
        $openid = !empty($data['openid'])?$data['openid']:'';
        $category = !empty($data['filter'])?$data['filter']:'';
        $role_ids = !empty($data['role_ids'])?$data['role_ids']:'';
        $page  = !empty($data['page'])?$data['page']:1;
        $sort  = !empty($data['sort'])?$data['sort']:'1';
        $tag  = !empty($data['tag'])?$data['tag']:'';
        $is_backend = !empty($this->request->header()['request-preview'])?$this->request->header()['request-preview']:0;

        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('team')
                ->check([
                    'page' => $page,
                ]);

            $list = (new GenshinTeam())->teamList($is_backend,$category,$tag,$role_ids,$openid,[
                ['is_publish','=',1]
            ],$sort,$page);
            return $this->success('success',$list['data'],array(
                'total' => $list['total'],
                'current_page' => $list['current_page'],
                'last_page' => $list['last_page'],
                'per_page' => $list['per_page'],
            ));
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }
    }


    /**
     * 组队详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function teamDetail(){
        $data = input('post.');
        $team_id = !empty($data['team_id'])?$data['team_id']:'';
        $openid = !empty($data['openid'])?$data['openid']:'';
        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('team_detail')
                ->check([
                    'team_id' => $team_id
                ]);

            $detail = (new \app\model\api\GenshinTeam())->teamDetail($team_id,$openid);
            return $this->success('success',$detail);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }
    }


    /**
     * 收藏/取消收藏
     */
    public function like(){
        $data = input('post.');
        $openid = !empty($data['openid'])?$data['openid']:'';
        $team_id = !empty($data['team_id'])?$data['team_id']:'';

        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('like')
                ->check([
                    'team_id' => $team_id,
                    'openid' => $openid
                ]);

            $genshinLikeModel = new GenshinLike();
            $genshinTeamModel = new GenshinTeam();
            $like_ids = $genshinLikeModel->getLike($openid);
            $teamInfo = $genshinTeamModel->where(array('id' => $team_id))->find();
            Db::startTrans();
            if(in_array($team_id,$like_ids)){
                $res = $genshinLikeModel->where(array('team_id' => $team_id))->cache('genshin_like'.$openid)->save(array('delete_time' => time()));
                $like_num = $teamInfo['like_num'] - 1 < 0 ?0:$teamInfo['like_num'] - 1;
            }else{
                $res = $genshinLikeModel->cache('genshin_like'.$openid)->save(array(
                    'openid' => $openid,
                    'team_id' => $team_id,
                ));
                $like_num = $teamInfo['like_num'] + 1 < 0 ?0:$teamInfo['like_num'] + 1;
            }
            $like_res = $genshinTeamModel->where(array('id' => $team_id))
                ->save(['like_num' => $like_num]);
            if($res === false || $like_res === false){
                Db::rollback();
                return $this->error('点赞失败',[]);
            }
            Db::commit();
            return $this->success('success',[
                'like_num' => $like_num
            ]);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }
    }


    /**
     * 收藏/取消收藏
     */
    public function collect(){
        $data = input('post.');
        $openid = !empty($data['openid'])?$data['openid']:'';
        $team_id = !empty($data['team_id'])?$data['team_id']:'';

        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('collect')
                ->check([
                    'team_id' => $team_id,
                    'openid' => $openid
                ]);

            $genshinCollectModel = new GenshinCollect();
            $collect_ids = $genshinCollectModel->getCollect($openid);

            if(in_array($team_id,$collect_ids)){
                $res = $genshinCollectModel->where(array('team_id' => $team_id))->cache('genshin_collect'.$openid)->save(array('delete_time' => time()));
            }else{
                $res = $genshinCollectModel->cache('genshin_collect'.$openid)->save(array(
                    'openid' => $openid,
                    'team_id' => $team_id,
                ));
            }

            if($res === false){
                return $this->error('收藏失败',[]);
            }

            return $this->success('success',[]);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),-1);
        }
    }




    /**
     * 我的收藏
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function collectList(){
        $data = input('post.');
        $page = !empty($data['page'])?$data['page']:1;
        $limit = !empty($data['limit'])?$data['limit']:10;
        $openid = !empty($data['openid'])?$data['openid']:'';
        $is_backend = !empty($this->request->header()['request-preview'])?$this->request->header()['request-preview']:0;

        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('collect_list')
                ->check([
                    'page' => $page,
                    'limit' => $limit,
                    'openid' => $openid
                ]);

            $genshinCollectModel = new GenshinCollect();
            $collect_ids = $genshinCollectModel->getCollect($openid);

            $where = array();
            $where[] = ['id','in',$collect_ids];
            $where[] = ['is_publish','=',1];
            $teamList = (new GenshinTeam())->teamList($is_backend,'','','',$openid,$where,2);

            return $this->success('success',$teamList['data'],array(
                'total' => $teamList['total'],
                'current_page' => $teamList['current_page'],
                'last_page' => $teamList['last_page'],
                'per_page' => $teamList['per_page'],
            ));

            //return $this->success('success',$teamList);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),[]);
        }
    }


    /**
     * 我的发布
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function publishList(){
        $data = input('post.');
        $page = !empty($data['page'])?$data['page']:1;
        $limit = !empty($data['limit'])?$data['limit']:10;
        $openid = !empty($data['openid'])?$data['openid']:'';
        $is_backend = !empty($this->request->header()['request-preview'])?$this->request->header()['request-preview']:0;

        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('collect_list')
                ->check([
                    'page' => $page,
                    'limit' => $limit,
                    'openid' => $openid
                ]);
            $where = array();
            $where[] = ['author_id','=',$openid];
            $teamList = (new GenshinTeam())->teamList($is_backend,'','','',$openid,$where,2);

            return $this->success('success',$teamList['data'],array(
                'total' => $teamList['total'],
                'current_page' => $teamList['current_page'],
                'last_page' => $teamList['last_page'],
                'per_page' => $teamList['per_page'],
            ));

            //return $this->success('success',$teamList);
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),[]);
        }
    }


    /**
     * 删除我的发布
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete(){
        $data = input('post.');
        $team_id = !empty($data['team_id'])?$data['team_id']:'';
        $openid = !empty($data['openid'])?$data['openid']:'';

        try{
            //验证器
            validate(\app\validate\api\Genshin::class)
                ->scene('like')
                ->check([
                    'team_id' => $team_id,
                    'openid' => $openid
                ]);
            $where = array();
            $where[] = ['author_id','=',$openid];
            $where[] = ['id','=',$team_id];

            $genshinTeamModel = new GenshinTeam();
            $team_info = $genshinTeamModel->where($where)->find();
            if(empty($team_info)){
                return $this->error('数据不存在');
            }

            $res = $team_info->delete();
            if(!$res){
                return $this->error('删除失败');
            }
            return $this->success('success');
        }catch (ValidateException $exception){
            return $this->error($exception->getMessage(),[]);
        }
    }


}
